package com.winning.sx.microframework.plugins.wx;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.ContextLoader;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.servlet.ServletContext;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.*;
import java.security.cert.CertificateException;
import java.util.HashMap;
import java.util.Map;

@Service
@Transactional
public class WxService {
    private static final Logger log = Logger.getLogger(WxService.class);

    public Map queryRefund(String orderid) throws Exception {
        Map<String, String> params = new HashMap<>();
        params.put("appid", WxConfig.appid);
        params.put("mch_id", WxConfig.mch_id2);
        params.put("nonce_str", WXPayUtil.generateNonceStr());
        params.put("sign_type", WxConfig.sign_type);
        params.put("out_refund_no", orderid);

        params.put("sign", WXPayUtil.generateSignature(params, WxConfig.key2));
        String paramsXml = WXPayUtil.mapToXml(params);

        log.info("查询退款结果:向微信发送请求的时候,map转成xml转成的字符串是:" + paramsXml);
        String paramsJson = sendPostNeedCert(paramsXml);
        log.info("查询退款结果:微信请求返回的数据是:" + paramsJson);
        Map<String, String> payMap = WXPayUtil.xmlToMap(paramsJson);
        return payMap;
    }

    private String sendPostNeedCert(String mapXmlStr)
            throws FileNotFoundException, KeyStoreException, IOException, NoSuchAlgorithmException,
            CertificateException, UnrecoverableKeyException, KeyManagementException, ClientProtocolException {
//        ServletContext context = ContextLoader.getCurrentWebApplicationContext().getServletContext();
//        String contextPath = context.getContextPath();
//        log.info("contextPath----------------->>" + contextPath);
        String targetPath = WxConfig.apiclientCert;
        InputStream certStream = new FileInputStream(targetPath);
        KeyStore ks = KeyStore.getInstance("PKCS12");
        ks.load(certStream, WxConfig.mch_id.toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, WxConfig.mch_id.toCharArray());

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(kmf.getKeyManagers(), null, new SecureRandom());

        SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
                new String[]{"TLSv1"}, null, new DefaultHostnameVerifier());
        BasicHttpClientConnectionManager connManager = new BasicHttpClientConnectionManager(RegistryBuilder
                .<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", sslConnectionSocketFactory).build(), null, null, null);
        HttpClient httpClient = HttpClientBuilder.create().setConnectionManager(connManager).build();

        // String downloadfundflowStr = HttpUtils.post(WxInfo.downloadfundflow,
        // mapXmlStr);
        HttpPost httpPost = new HttpPost(WxConfig.refundQuery);

        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(2000).build();
        httpPost.setConfig(requestConfig);

        StringEntity postEntity = new StringEntity(mapXmlStr, "UTF-8");
        httpPost.addHeader("Content-Type", "text/xml");
        httpPost.addHeader("User-Agent", "wxpay sdk java v1.0 " + WxConfig.mch_id); // TODO:
        // 很重要，用来检测
        // sdk
        // 的使用情况，要不要加上商户信息？
        httpPost.setEntity(postEntity);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        String downloadfundflowStr = EntityUtils.toString(httpEntity, "UTF-8");
        return downloadfundflowStr;
    }

}